<?php

class Main {

    public function __construct($id = false) {
        $this->DB = Database::Init();
        $this->site = $this->GetSite($id);        
        $this->site->template_path = TEMPLATES_DIR . "/" . $this->site->template;
        $this->site->template_uri = "/frostcore/templates/" . $this->site->template;
        $tpl_folder = $this->site->template_path;
        if (!is_dir($tpl_folder)) {
            mkdir($tpl_folder, DIR_MODE, true);
            $header = fopen($tpl_folder . "/header.php", 'w');
            $footer = fopen($tpl_folder . "/footer.php", 'w');
            fclose($header);
            fclose($footer);
        }
        if (!is_dir(ROOT_DIR . $this->site->dir . "uploads")) {
            Filesystem::makeDir(ROOT_DIR . $this->site->dir . "uploads");
        }
    }

    public function GetSite($id = false) {                
        $result = $this->DB
                ->select()
                ->fields(array("site.*", "lang.code" => "language", "tpl.code" => "template"))
                ->table('site__settings', 'site')
                ->table('site__languages', 'lang')
                ->table('site__templates', 'tpl');
        if ($id) {
            if (is_int($id)) {
                $result->cond('site.id', $id);
            }else{
                $result->cond('site.code', $id);
            }
        } else {
            $result->cond('is_default', Y);
        }
        $result->cond('lang.id', 'site.language')->noquotes()
                ->cond('tpl.id', 'site.template')->noquotes();
        $data = $result->exec();
        return $data->fetchObj();
    }
    
    function CreateSite($data = false){
        BDS::Init('site__settings');
        if(!$data){
            $id = BDS::Info('Auto_increment');
            $data = array(
                'id' => $id,
                'code' => "site_".$id,
                'title' => "Site ".$id,
                'dir' => "/site_$id/",
            );
        }
        
        if($data['dir'] != "/"){
            $content = '<? require_once $_SERVER["DOCUMENT_ROOT"] . "/frostcore/header.php"; ?>
CONTENT...                
<? require_once $_SERVER["DOCUMENT_ROOT"] . "/frostcore/footer.php"; ?>';
            Filesystem::createFile(ROOT_DIR.$data['dir']."index.php", $content);            
        }
        $result = BDS::Create($data);
        return $result->isTrue();
    }
    
    function DeleteSite($id, $use_backup = false){        
        $delSite = $this->GetSite($id);
        if($use_backup){
            $this->BackupSite($id);
        }
        if($delSite->dir != "/"){
            $path = substr($delSite->dir, 0, strlen($delSite->dir) -1);
            Filesystem::removeDir(ROOT_DIR.$path);
        }
        BDS::Init('site__settings');
        $result = BDS::Delete($id);
        return $result->isTrue();
    }
    
    function UpdateSite($id, $data){
        BDS::Init('site__settings');
        $updSite = $this->GetSite($id);
        if(isset($data['dir'])){
            $from = ROOT_DIR.$updSite->dir;
            $to = ROOT_DIR.$data['dir'];
            Filesystem::moveDir($from, $to);
        }
        $result = BDS::Update($id, $data);
        return $result->isTrue();
    }
    
    function BackupSite($id, $use_db_dump = true){
        $backup = $this->GetSite($id);
        $path = substr($backup->dir, 0, strlen($backup->dir) -1);
        $zipname = Filesystem::CreateBackup(ROOT_DIR.$path, $backup->code);
        
        if($use_db_dump){            
            $tmp = ROOT_DIR."/frostcore/backup/tmp";
            if(is_dir($tmp)){
                Filesystem::removeDir($tmp);
            }
            mkdir($tmp);
            $tables = $this->DB->getTables();
            $zip = new ZipArchive();
            foreach ($tables as $table){
                $file = $tmp."/$table"."_dump.csv";
                $sql = "SELECT * FROM $table, site__templates INTO OUTFILE '$file' LINES TERMINATED BY '\n'";
                $this->DB->native($sql)->exec();                
                $zip->open($zipname);
                $zip->addEmptyDir("dump");
                $zip->addFile($file, "dump/".$table."_dump.csv");                
            }
            $ok = $zip->close();
            Filesystem::removeDir($tmp);
        }
        return $ok;
    }

    public static function GetHeadScripts() {
        print Buffer::Get('HEAD_SCRIPTS');
    }

    public static function GetHeadStyles() {
        print Buffer::Get('HEAD_STYLES');
    }

    public static function AddHeadScript($uri) {
        $str = "<script type=\"text/javascript\" src=\"$uri\"></script>";
        print Buffer::Add('HEAD_SCRIPTS', $str);
    }

    public static function AddHeadStyle($uri) {
        preg_match("#(less|css)$#si", $uri, $m);
        $ext = $m[1];
        $less = $ext == "less" ? "/less" : false;
        $str = "<link type=\"text/css\" href=\"$uri\" rel=\"stylesheet$less\" />";
        Buffer::Add('HEAD_STYLES', $str);
    }

    static function Component($ns, $name, $params = array(), $template = false) {
        $template = $template ? $template : "default";
        $filename = COMPONENTS_DIR . "/$ns/$name/$name.com.php";        
        if (file_exists($filename)) {
            include $filename;
        }
        $tpl = $filename = COMPONENTS_DIR . "/$ns/$name/views/$template/view.php";
        if (file_exists($tpl)) {
            include $tpl;
        }
    }

}
